package com.stlm2.dems.service;

import com.stlm2.core.common.md5.MD5;
import com.stlm2.core.common.page.PageView;
import com.stlm2.dems.dao.*;
import com.stlm2.dems.entity.*;
import com.stlm2.dems.user.dao.AccountDao;
import com.stlm2.dems.user.dao.LowerDao;
import com.stlm2.dems.user.dao.RoleDao;
import com.stlm2.dems.user.dao.UserRoleDao;
import com.stlm2.dems.user.entity.*;
import com.stlm2.util.Memcached;
import com.stlm2.util.codecontent.CodeContent;
import org.apache.commons.lang.math.NumberUtils;
import org.json.JSONObject;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;

import com.stlm2.core.base.BaseDao;
import com.stlm2.core.base.impl.BaseServiceImpl;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service("ddmShopService")
@Transactional(rollbackForClassName={"java.lang.Exception"}, propagation = Propagation.REQUIRED)
public class DdmShopService extends BaseServiceImpl<DdmShop> {

	@Resource
	private DdmShopDao ddmShopDao;
	@Resource
	private UserDao userDao;
	@Resource
	private Memcached memcached;
	@Resource
	private ShopAdminUserDao shopAdminUserDao;
	@Resource
	private UserRoleDao userRoleDao;
	@Resource
	private LowerDao lowerDao;
	@Resource
	private AccountDao accountDao;
	@Resource
	private RoleDao roleDao;
	@Resource
	private DdmGoodsDao ddmGoodsDao;
	@Resource
	private SpecificationDao specificationDao;
	@Resource
	private GoodSpecificationDao goodSpecificationDao;
	@Resource
	private InventoryDao inventoryDao;



	@Override
	protected BaseDao <DdmShop> getDao() {
		return ddmShopDao;
	}
	/*
	*zlq
	* 添加店铺
	* token:
	* name: 店铺名称
	* mainImg： 店铺主图
	* datailImg： 店铺详情图
	* location：店铺地址
	* contact： 店铺联系方式
	* linkman：店铺联系人
	* longitudeAndLatitude:经纬度
	* shopTypeValue:店铺类型 1：自营 2：他营
	* shopLevelValue：店铺等级
	*
	 */
	public String add(ModelMap model, String token,String name,String mainImg,String datailImg,String location,String contact,String linkman,String longitudeAndLatitude,String shopTypeValue,String  shopLevelValue ){
		if (StringUtils.isEmpty(token)) {
			return CodeContent.getModelByCode(-1, "", model);
		}
		User loginUser = userDao.getByToken(token);
		if (loginUser == null) {
			return CodeContent.getModelByCode(-1, "", model);
		}
		if (StringUtils.isEmpty(name)) {
			return CodeContent.getModelByCode(0, "店铺名称不能为空", model);
		}
		if (StringUtils.isEmpty(mainImg)) {
			return CodeContent.getModelByCode(0, "店铺主图不能为空", model);
		}
		if (StringUtils.isEmpty(datailImg)) {
			return CodeContent.getModelByCode(0, "店铺详情图不能为空", model);
		}
		if (StringUtils.isEmpty(location)) {
			return CodeContent.getModelByCode(0, "店铺地址不能为空", model);
		}
		if (StringUtils.isEmpty(contact)) {
			return CodeContent.getModelByCode(0, "店铺联系方式不能为空", model);
		}
		if (StringUtils.isEmpty(linkman)) {
			return CodeContent.getModelByCode(0, "店铺联系人不能为空", model);
		}
		if(!NumberUtils.isDigits(shopTypeValue)){
			return CodeContent.getModelByCode(0, "店铺类型不能为空", model);
		}
		if(ShopType.getByIntValue(Integer.parseInt(shopTypeValue))==null){
			return CodeContent.getModelByCode(0, "店铺类型不正确", model);
		}

		if(!NumberUtils.isDigits(shopLevelValue)){
			return CodeContent.getModelByCode(0, "店铺等级不能为空", model);
		}
		if(ShopLevel.getByIntValue(Integer.parseInt(shopLevelValue))==null){
			return CodeContent.getModelByCode(0, "店铺等级不正确", model);
		}

		if (StringUtils.isEmpty(longitudeAndLatitude)) {
			return CodeContent.getModelByCode(0, "经纬度不能为空", model);
		}
		//防止重复提交
		Object o = memcached.get(loginUser.getId()+"ADDddmGoods");
		if(o!=null){
			return CodeContent.getModelByCode(0, "您操作频繁，请在10秒后重试", model);
		}else {
			memcached.set(loginUser.getId()+"ADDddmGoods",10,"1");
		}
		DdmShop ddmShop=new DdmShop();
		ddmShop.setName(name.trim());
		ddmShop.setMainImg(mainImg.trim());
		ddmShop.setDatailImg(datailImg.trim());
		ddmShop.setLocation(location.trim());
		ddmShop.setContact(contact.trim());
		ddmShop.setLinkman(linkman.trim());
		ddmShop.setState(false);
		ddmShop.setCreateUserId(loginUser.getId());
		ddmShop.setCreateTime(new Date());
		ddmShop.setLongitudeAndLatitude(longitudeAndLatitude);
		ddmShop.setShopTypeValue(Integer.parseInt(shopTypeValue));
		ddmShop.setShopLevelValue(Integer.parseInt(shopLevelValue));
		ddmShopDao.add(ddmShop);
		UserRole userRole=new UserRole();
		userRole.setRoleId(AllRole.SystemAdmin.getIntValue());
		List<UserRole > userRoleList=userRoleDao.queryPageView(-1,-1,userRole).getRecords();
		for(UserRole userRole1:userRoleList){
			ShopAdminUser shopAdminUser=new ShopAdminUser();
			shopAdminUser.setShopId(ddmShop.getId());
			shopAdminUser.setUserId(userRole1.getUserId());
			shopAdminUser.setCreateTime(new Date());
			shopAdminUser.setCreateUserId(loginUser.getId());
			shopAdminUserDao.add(shopAdminUser);
		}

		return CodeContent.getModelByCode(1, "", model);
	}

	/*
	*CRM查询店铺列表
	* zlq
	* token:
	* page:页码
	* name:店铺名称
	* location：店铺地址
	* state：店铺状态 true：有效 false：无效 不传为所有
	* shopTypeValue：店铺类型 1：自营 2：他营
	* shopLevelValue:店铺等级
	 */
	public String getList(ModelMap model, String token,String page,String name,String location,Boolean state,String shopTypeValue,String  shopLevelValue){
		PageView pageview = new PageView();
		int pageNo = 1;
		int pageSize = 20;
		if (NumberUtils.isDigits(page) && !"0".equals(page.trim())) {
			pageNo = NumberUtils.toInt(page);
		}
		if (StringUtils.isEmpty(token)) {
			return CodeContent.getModelByCode(-1, "", model);
		}
		User loginUser = userDao.getByToken(token);
		if (loginUser == null) {
			return CodeContent.getModelByCode(-1, "", model);
		}
		DdmShop ddmShop=new DdmShop();
		if(!StringUtils.isEmpty(name)){
			ddmShop.setName(name.trim());
		}
		if(!StringUtils.isEmpty(location)){
			ddmShop.setLocation(location.trim());
		}
		if (NumberUtils.isDigits(shopTypeValue)) {
			ddmShop.setShopTypeValue(Integer.parseInt(shopTypeValue));
		}
		if (NumberUtils.isDigits(shopLevelValue)) {
			ddmShop.setShopLevelValue(Integer.parseInt(shopLevelValue));
		}
		ddmShop.setState(state);
		pageview=ddmShopDao.queryPageView(pageNo, pageSize,ddmShop);
		model.put("code",1);
		model.put("msg","success");
		if (pageview != null){
			model.put("datas",convertCrmList(pageview.getRecords()));
			model.put("recordsTotal", pageview.getRowCount());
			model.put("totalPage", pageview.getPageCount());
			model.put("pageNow", pageview.getPageNow());
		}

		return new JSONObject(model).toString();
	}
	public List<ModelMap> convertCrmList(List<DdmShop> ddmShopList) {
		List<ModelMap> list = new ArrayList<ModelMap>();
		if (ddmShopList != null && ddmShopList.size() > 0) {
			for (DdmShop ddmShop : ddmShopList) {
				ModelMap map = buildModelCrmList(ddmShop);
				list.add(map);
			}
		}
		return list;
	}
	public ModelMap buildModelCrmList(DdmShop ddmShop) {
		ModelMap model = new ModelMap();
		model.put("id",ddmShop.getId());
		model.put("name",ddmShop.getName());
		model.put("shopType",ddmShop.getShopType().toString());
		model.put("linkman",ddmShop.getLinkman());
		model.put("contact",ddmShop.getContact());
		model.put("location",ddmShop.getLocation());
		model.put("state",ddmShop.getState()?"有效":"无效");
		model.put("shopLevel",ddmShop.getShopLevel().toString());
		model.put("longitudeAndLatitude",ddmShop.getLongitudeAndLatitude());

		return  model;
	}

	/*
	*zlq
	* crm查询店铺详情
	* token:
	* id:店铺ID
	 */
	public String crmDetails(ModelMap model,String token,String id){
		if (StringUtils.isEmpty(token)) {
			return CodeContent.getModelByCode(-1, "", model);
		}
		User loginUser = userDao.getByToken(token);
		if (loginUser == null) {
			return CodeContent.getModelByCode(-1, "", model);
		}
		if (!NumberUtils.isDigits(id)) {
			return CodeContent.getModelByCode(0, "ID不能为空", model);
		}
		DdmShop ddmShop=ddmShopDao.getById(Integer.parseInt(id));
		if(ddmShop==null){
			return CodeContent.getModelByCode(0, "店铺ID不存在", model);
		}
		return CodeContent.getModelByCode(1, "", buildModelCrmDetails(ddmShop));
	}
	public ModelMap buildModelCrmDetails(DdmShop ddmShop) {
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		ModelMap model = new ModelMap();
		model.put("id",ddmShop.getId());
		model.put("state",ddmShop.getState()?"有效":"无效");
		model.put("shopLevel",ddmShop.getShopLevel().toString());
		model.put("name",ddmShop.getName());
		model.put("shopType",ddmShop.getShopType().toString());
		model.put("linkman",ddmShop.getLinkman());
		model.put("contact",ddmShop.getContact());
		model.put("location",ddmShop.getLocation());
		model.put("createTime",formatter.format(ddmShop.getCreateTime()));
		User createUser=userDao.getById(ddmShop.getCreateUserId());
		model.put("createUser",createUser.getRealName());
		model.put("mainImg",ddmShop.getMainImg());
		model.put("datailImg",ddmShop.getDatailImg());
		model.put("longitudeAndLatitude",ddmShop.getLongitudeAndLatitude());
		return  model;
	}

	public String allshopSelect(ModelMap model){
		List<ModelMap> list = new ArrayList<ModelMap>();
		DdmShop ddmShop=new DdmShop();
		ddmShop.setState(true);
		List <DdmShop> ddmShopList=ddmShopDao.queryPageView(-1,-1,ddmShop).getRecords();
		for(DdmShop ddmShop1:ddmShopList){
			ModelMap mode2 = new ModelMap();
			mode2.put("id",ddmShop1.getId());
			mode2.put("name",ddmShop1.getName());
			list.add(mode2);
		}
		return CodeContent.getModelByCode(1, "", list);
	}


    public String findShopLocations() {
		return ddmShopDao.findShopLocations();
    }
	public  String getPortalShopList(ModelMap modelMap,String page){
		PageView pageview = new PageView();
		int pageNo = 1;
		int pageSize = 20;
		if (NumberUtils.isDigits(page) && !"0".equals(page.trim())) {
			pageNo = NumberUtils.toInt(page);
		}
		DdmShop ddmShop =new DdmShop();
		ddmShop.setState(true);
		ddmShop.setShopLevel(ShopLevel.Shop);
		pageview=ddmShopDao.queryPageView(pageNo, pageSize,ddmShop);

		return CodeContent.getModelByCode(1, "", convertCrmList(pageview.getRecords()));
	}


	/*
	*zlq
	* 修改店铺
	* token:
	* id：店铺Id
	* name: 店铺名称
	* mainImg： 店铺主图
	* datailImg： 店铺详情图
	* location：店铺地址
	* contact： 店铺联系方式
	* linkman：店铺联系人
	* longitudeAndLatitude:经纬度
	* shopTypeValue:店铺类型 1：自营 2：他营
	* shopLevelValue：店铺等级
	*
	 */
	public String modification(ModelMap model,String token,String id,String name,String mainImg,String datailImg,String location,String contact,String linkman,String longitudeAndLatitude,String shopTypeValue,String  shopLevelValue){
		if (StringUtils.isEmpty(token)) {
			return CodeContent.getModelByCode(-1, "", model);
		}
		User loginUser = userDao.getByToken(token);
		if (loginUser == null) {
			return CodeContent.getModelByCode(-1, "", model);
		}
		if(!NumberUtils.isDigits(id)){
			return CodeContent.getModelByCode(0, "店铺ID不能为空", model);
		}
		if (StringUtils.isEmpty(name)) {
			return CodeContent.getModelByCode(0, "店铺名称不能为空", model);
		}
		if (StringUtils.isEmpty(mainImg)) {
			return CodeContent.getModelByCode(0, "店铺主图不能为空", model);
		}
		if (StringUtils.isEmpty(datailImg)) {
			return CodeContent.getModelByCode(0, "店铺详情图不能为空", model);
		}
		if (StringUtils.isEmpty(location)) {
			return CodeContent.getModelByCode(0, "店铺地址不能为空", model);
		}
		if (StringUtils.isEmpty(contact)) {
			return CodeContent.getModelByCode(0, "店铺联系方式不能为空", model);
		}
		if (StringUtils.isEmpty(linkman)) {
			return CodeContent.getModelByCode(0, "店铺联系人不能为空", model);
		}
		if(!NumberUtils.isDigits(shopTypeValue)){
			return CodeContent.getModelByCode(0, "店铺类型不能为空", model);
		}
		if(ShopType.getByIntValue(Integer.parseInt(shopTypeValue))==null){
			return CodeContent.getModelByCode(0, "店铺类型不正确", model);
		}

		if(!NumberUtils.isDigits(shopLevelValue)){
			return CodeContent.getModelByCode(0, "店铺等级不能为空", model);
		}
		if(ShopLevel.getByIntValue(Integer.parseInt(shopLevelValue))==null){
			return CodeContent.getModelByCode(0, "店铺等级不正确", model);
		}

		if (StringUtils.isEmpty(longitudeAndLatitude)) {
			return CodeContent.getModelByCode(0, "经纬度不能为空", model);
		}
		DdmShop ddmShop=ddmShopDao.getById(Integer.parseInt(id));
		if(ddmShop==null){
			return CodeContent.getModelByCode(0, "店铺ID不存在", model);
		}
		//防止重复提交
		Object o = memcached.get(loginUser.getId()+"modification");
		if(o!=null){
			return CodeContent.getModelByCode(0, "您操作频繁，请在10秒后重试", model);
		}else {
			memcached.set(loginUser.getId()+"modification",10,"1");
		}
		ddmShop.setName(name.trim());
		ddmShop.setMainImg(mainImg.trim());
		ddmShop.setDatailImg(datailImg.trim());
		ddmShop.setLocation(location.trim());
		ddmShop.setContact(contact.trim());
		ddmShop.setLinkman(linkman.trim());
		ddmShop.setUpdateUserId(loginUser.getId());
		ddmShop.setUpdateTime(new Date());
		ddmShop.setLongitudeAndLatitude(longitudeAndLatitude);
		ddmShop.setShopTypeValue(Integer.parseInt(shopTypeValue));
		ddmShop.setShopLevelValue(Integer.parseInt(shopLevelValue));
		ddmShopDao.modify(ddmShop);
		return CodeContent.getModelByCode(1, "", model);
	}
	/*
	*启用店铺并铺货
	* zlq
	*
	 */
	public String shopStart(ModelMap model,String token,String id){
		if (StringUtils.isEmpty(token)) {
			return CodeContent.getModelByCode(-1, "", model);
		}
		User loginUser = userDao.getByToken(token);
		if (loginUser == null) {
			return CodeContent.getModelByCode(-1, "", model);
		}
		if(!NumberUtils.isDigits(id)){
			return CodeContent.getModelByCode(0, "店铺ID不能为空", model);
		}
		//防止重复提交
		Object o = memcached.get(id+"shopStart");
		if(o!=null){
			return CodeContent.getModelByCode(0, "店铺正在启用并初始化库存中，请在5分钟后重试", model);
		}else {
			memcached.set(id+"shopStart",300,"1");
		}
		DdmShop ddmShop=ddmShopDao.getById(Integer.parseInt(id));
		if(ddmShop==null){
			return CodeContent.getModelByCode(0, "店铺ID不存在", model);
		}
		if(ddmShop.getState()){
			return CodeContent.getModelByCode(0, "店铺已经启用", model);
		}
		List <DdmGoods> goodsList=ddmGoodsDao.queryPageView(-1,-1,new DdmGoods()).getRecords();
		for(DdmGoods ddmGoods : goodsList){
			GoodSpecification goodSpecification =new GoodSpecification();
			goodSpecification.setGoodId(ddmGoods.getId());
			goodSpecification.setGoodsState(true);
			List <GoodSpecification> goodSpecificationList=goodSpecificationDao.queryPageView(-1,-1,goodSpecification).getRecords();
			if(goodSpecificationList.size()!=0){
				for(GoodSpecification goodSpecification1:goodSpecificationList){
					Inventory inventory=inventoryDao.getOnlyInventory(ddmShop.getId(),ddmGoods.getId(),goodSpecification1.getId());
					if(inventory==null){
						inventory=new Inventory();
						inventory.setGoodsId(ddmGoods.getId());
						inventory.setShopId(ddmShop.getId());
						inventory.setSpeciflcationId(goodSpecification1.getId());
						inventory.setTotalInventory(0);
						inventory.setInventory(0);
						inventory.setCreateTime(new Date());
						inventory.setCreateUserId(loginUser.getId());
						inventoryDao.add(inventory);
					}
				}
			}else {
				Inventory inventory=inventoryDao.getOnlyInventory(ddmShop.getId(),ddmGoods.getId(),null);
				if(inventory==null){
					inventory=new Inventory();
					inventory.setGoodsId(ddmGoods.getId());
					inventory.setShopId(ddmShop.getId());
					inventory.setTotalInventory(0);
					inventory.setInventory(0);
					inventory.setCreateTime(new Date());
					inventory.setCreateUserId(loginUser.getId());
					inventoryDao.add(inventory);
				}
			}
		}
		ddmShop.setState(true);
		ddmShopDao.modify(ddmShop);
		return CodeContent.getModelByCode(1, "", model);
	}

	public String invalidShop(ModelMap model,String token,String id){
		if (StringUtils.isEmpty(token)) {
			return CodeContent.getModelByCode(-1, "", model);
		}
		User loginUser = userDao.getByToken(token);
		if (loginUser == null) {
			return CodeContent.getModelByCode(-1, "", model);
		}
		if(!NumberUtils.isDigits(id)){
			return CodeContent.getModelByCode(0, "店铺ID不能为空", model);
		}
		//防止重复提交
		Object o = memcached.get(id+"invalidShop");
		if(o!=null){
			return CodeContent.getModelByCode(0, "店铺正在启用并初始化库存中，请在10秒后重试", model);
		}else {
			memcached.set(id+"invalidShop",10,"1");
		}
		DdmShop ddmShop=ddmShopDao.getById(Integer.parseInt(id));
		if(ddmShop==null){
			return CodeContent.getModelByCode(0, "店铺ID不存在", model);
		}
		if(!ddmShop.getState()){
			return CodeContent.getModelByCode(0, "店铺已经无效", model);
		}
		ddmShop.setState(false);
		ddmShopDao.modify(ddmShop);
		return CodeContent.getModelByCode(1, "", model);
	}

}